package com.gpframework.module.controller.wages;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gpframework.common.annotation.Log;
import com.gpframework.common.core.controller.BaseController;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.page.TableDataInfo;
import com.gpframework.common.enums.BusinessType;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.exception.BaseException;
import com.gpframework.common.utils.poi.ExcelUtil;
import com.gpframework.module.wages.domain.GzPersonnelFoundation;
import com.gpframework.module.wages.domain.GzSalaryLevelBase;
import com.gpframework.module.wages.domain.GzSalaryLevelTransferWarehouseWorkers;
import com.gpframework.module.wages.domain.GzWarehouseWorkerSalaryLevel;
import com.gpframework.module.wages.domain.req.GzPersonnelFoundationAdd;
import com.gpframework.module.wages.domain.req.GzPersonnelFoundationReq;
import com.gpframework.module.wages.domain.req.GzPersonnelFoundationUpdate;
import com.gpframework.module.wages.domain.vo.*;
import com.gpframework.module.wages.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName GzPersonnelFoundationController
 * @Author gpframework
 * @Date 2024-01-18
 * @Version 1.0.0
 * @Description 人员基础Controller
 */
@Validated
@Api(tags = "人员基础")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@SuppressWarnings({"rawtypes","unchecked"})
@RequestMapping("/wages/personnelfoundation" )
public class GzPersonnelFoundationController extends BaseController {

    private final IGzPersonnelFoundationService iGzPersonnelFoundationService;

    private final IGzMonthlyLeaveService iGzMonthlyLeaveService;

    private final IGzSalaryLevelTransferWarehouseWorkersService iGzSalaryLevelTransferWarehouseWorkersService;


    private final IGzWarehouseWorkerSalaryLevelService iGzWarehouseWorkerSalaryLevelService;

    private final IGzSalaryLevelBaseService iGzSalaryLevelBaseService;

    /**
     * @Description 分页
     * @Author gpframework
     * @Date 2024-01-18
     * @Param gzPersonnelFoundation
     * @Return TableDataInfo
     */
    @ApiOperation("列表")
    @PreAuthorize("@ss.hasPermi('wages:personnelfoundation:list')")
    @GetMapping("/list")
    public TableDataInfo<GzPersonnelFoundationVo> list(GzPersonnelFoundationReq gzPersonnelFoundationReq) {
        startPage();
        QueryWrapper<GzPersonnelFoundation> lqw = new QueryWrapper<GzPersonnelFoundation>();
        gzPersonnelFoundationReq.generatorQuery(lqw, true);
        List<GzPersonnelFoundationVo> list = iGzPersonnelFoundationService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-01-18
     * @Param gzPersonnelFoundation
     * @Return TableDataInfo
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('wages:personnelfoundation:add')")
    @Log(title = "添加人员基础", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody GzPersonnelFoundationAdd gzPersonnelFoundationAdd) {
        GzPersonnelFoundation gzPersonnelFoundation = Convert.convert(new TypeReference<GzPersonnelFoundation>() {
        }, gzPersonnelFoundationAdd);

        //新增销售档次基础表
        GzSalaryLevelBase salaryLevelBase = iGzSalaryLevelBaseService.getOne(new LambdaQueryWrapper<GzSalaryLevelBase>()
                .eq(GzSalaryLevelBase::getSalesLevel, gzPersonnelFoundationAdd.getSalesLevel())
                .eq(GzSalaryLevelBase::getDelStatus, YesNoEnum.NO.getKey())
                .last("limit 1"));
        if (salaryLevelBase==null){
            GzSalaryLevelBase salaryLevelBaseAdd = new GzSalaryLevelBase();
            salaryLevelBaseAdd.setSalesLevel(gzPersonnelFoundationAdd.getSalesLevel());
            iGzSalaryLevelBaseService.save(salaryLevelBaseAdd);
        }
        return toAjax(iGzPersonnelFoundationService.save(gzPersonnelFoundation) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-01-18
     * @Param gzPersonnelFoundation
     * @Return TableDataInfo
     */
    @ApiOperation("修改")
    @PreAuthorize("@ss.hasPermi('wages:personnelfoundation:edit')")
    @Log(title = "修改人员基础", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody GzPersonnelFoundationUpdate gzPersonnelFoundationUpdate) {
        GzPersonnelFoundation gzPersonnelFoundation = Convert.convert(new TypeReference<GzPersonnelFoundation>() {
        }, gzPersonnelFoundationUpdate);
        //新增销售档次基础表
        GzSalaryLevelBase salaryLevelBase = iGzSalaryLevelBaseService.getOne(new LambdaQueryWrapper<GzSalaryLevelBase>()
                .eq(GzSalaryLevelBase::getSalesLevel, gzPersonnelFoundationUpdate.getSalesLevel())
                .eq(GzSalaryLevelBase::getDelStatus, YesNoEnum.NO.getKey())
                .last("limit 1"));
        if (salaryLevelBase==null){
            salaryLevelBase = new GzSalaryLevelBase();
            salaryLevelBase.setSalesLevel(gzPersonnelFoundationUpdate.getSalesLevel());
            iGzSalaryLevelBaseService.save(salaryLevelBase);
        }

        return toAjax(iGzPersonnelFoundationService.updateById(gzPersonnelFoundation) ? 1 : 0);
    }

    @ApiOperation("批量修改社保")
    @PreAuthorize("@ss.hasPermi('wages:personnelfoundation:edit')")
    @Log(title = "批量修改社保", businessType = BusinessType.UPDATE)
    @PutMapping("/editBachSocial")
    public AjaxResult editBachSocial(@RequestBody GzPersonnelFoundationUpdate gzPersonnelFoundationUpdate) {
        BigDecimal bachPersonalPortionOfSocialSecurity = gzPersonnelFoundationUpdate.getBachPersonalPortionOfSocialSecurity();
        if (bachPersonalPortionOfSocialSecurity.compareTo(BigDecimal.ZERO) > 0) {
            throw new BaseException("请输入负数、用来扣除社保");
        }
        for (Long id : gzPersonnelFoundationUpdate.getIds()) {
            iGzPersonnelFoundationService.update(new UpdateWrapper<GzPersonnelFoundation>()
                    .isNotNull("personal_portion_of_social_security")
                    .eq("id", id)
                    .set("personal_portion_of_social_security", bachPersonalPortionOfSocialSecurity));
        }

        return toAjax(true);
    }


    /**
     * @Description 导入
     * @Author gpframework
     * @Date 2023-06-16
     * @Param gpProductShelves
     * @Return TableDataInfo
     */
    @ApiOperation("下载模板")
    @PreAuthorize("@ss.hasPermi('wages:personnelfoundation:export')")
    @Log(title = "下载模板", businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<GzPersonnelFoundationVo> util = new ExcelUtil<GzPersonnelFoundationVo>(GzPersonnelFoundationVo.class);
        return util.importTemplateExcel("人员管理基础表");
    }

    /**
     * @Description 导入
     * @Author gpframework
     * @Date 2023-06-16
     * @Param gpProductShelves
     * @Return TableDataInfo
     */
    @ApiOperation("导入")
    @PreAuthorize("@ss.hasPermi('wages:personnelfoundation:add')")
    @Log(title = "导入", businessType = BusinessType.INSERT)
    @PostMapping("/import")
    public AjaxResult importList(MultipartFile file) throws Exception {
        if (file == null) {
            return AjaxResult.error("获取不到导入文件");
        }
        boolean excel = ExcelUtil.isExcel(file.getOriginalFilename());
        if (!excel) {
            return AjaxResult.error("导入文件格式错误，请导入excel文件");
        }
        // 导入新数据
        ExcelUtil<GzPersonnelFoundationVo> util = new ExcelUtil<GzPersonnelFoundationVo>(GzPersonnelFoundationVo.class);
        List<GzPersonnelFoundationVo> excelList = util.importCacheExcel(file.getInputStream());
        List<GzPersonnelFoundation> list = Convert.convert(new TypeReference<List<GzPersonnelFoundation>>() {
        }, excelList);



        for (GzPersonnelFoundation gzPersonnelFoundation : list) {
            // 删除旧数据 名字 部门相同的数据
            iGzPersonnelFoundationService.remove(new QueryWrapper<GzPersonnelFoundation>().eq("name", gzPersonnelFoundation.getName()).eq("department_name", gzPersonnelFoundation.getDepartmentName()).eq("del_status", YesNoEnum.NO.getKey()));

            //新增销售档次基础表
            GzSalaryLevelBase salaryLevelBase = iGzSalaryLevelBaseService.getOne(new LambdaQueryWrapper<GzSalaryLevelBase>()
                    .eq(GzSalaryLevelBase::getSalesLevel, gzPersonnelFoundation.getSalesLevel())
                    .eq(GzSalaryLevelBase::getDelStatus, YesNoEnum.NO.getKey())
                    .last("limit 1"));
            if (salaryLevelBase==null){
                salaryLevelBase = new GzSalaryLevelBase();
                salaryLevelBase.setSalesLevel(gzPersonnelFoundation.getSalesLevel());
                iGzSalaryLevelBaseService.save(salaryLevelBase);
            }


            //导入
            if (gzPersonnelFoundation.getSubclassIevel() != null || gzPersonnelFoundation.getSalaryLevel() != null) {
                // 中转仓员工资 基本工资数据
                if (gzPersonnelFoundation.getDepartmentType() == 2) {
                    GzSalaryLevelTransferWarehouseWorkers gzSalaryLevelTransferWarehouseWorkers = iGzSalaryLevelTransferWarehouseWorkersService.getOne(new LambdaQueryWrapper<GzSalaryLevelTransferWarehouseWorkers>()
                            .eq(GzSalaryLevelTransferWarehouseWorkers::getCategoryLevel, gzPersonnelFoundation.getSalaryLevel())
                            .eq(GzSalaryLevelTransferWarehouseWorkers::getSubclassLevel, gzPersonnelFoundation.getSubclassIevel())
                            .eq(GzSalaryLevelTransferWarehouseWorkers::getDelStatus, YesNoEnum.NO.getKey()));

                    gzPersonnelFoundation.setBasicSalary(gzSalaryLevelTransferWarehouseWorkers.getBaseSalary());
                    //岗位工资
                    gzPersonnelFoundation.setPostWage(gzSalaryLevelTransferWarehouseWorkers.getAllowance());
                    gzPersonnelFoundation.setManagementAllowance(gzSalaryLevelTransferWarehouseWorkers.getManagementAllowance());
                    gzPersonnelFoundation.setHouseaLlowance(gzSalaryLevelTransferWarehouseWorkers.getHouseaLlowance());
                    gzPersonnelFoundation.setServiceExperienceAward(gzSalaryLevelTransferWarehouseWorkers.getSeniorityPay());

                    gzPersonnelFoundation.setAchievementBonus(gzSalaryLevelTransferWarehouseWorkers.getAchievementBonus());
                    gzPersonnelFoundation.setEvaluationCriteriaBonus(gzSalaryLevelTransferWarehouseWorkers.getEvaluationCriteriaBonus());
                    gzPersonnelFoundation.setSocialSecuritySubsidies(gzSalaryLevelTransferWarehouseWorkers.getSocialSecuritySubsidies());
                    // 加班费 全勤奖
                    gzPersonnelFoundation.setFullAttendanceBonus(gzSalaryLevelTransferWarehouseWorkers.getFullAttendanceBonus());
                    gzPersonnelFoundation.setOvertimePay(gzSalaryLevelTransferWarehouseWorkers.getOvertimePay());
                }

                //仓储中心员工 基本工资数据
                if (gzPersonnelFoundation.getDepartmentType() == 3) {
                    GzWarehouseWorkerSalaryLevel gzWarehouseWorkerSalaryLevel = iGzWarehouseWorkerSalaryLevelService.getOne(new LambdaQueryWrapper<GzWarehouseWorkerSalaryLevel>()
                            .eq(GzWarehouseWorkerSalaryLevel::getCategoryLevel, gzPersonnelFoundation.getSalaryLevel())
                            .eq(GzWarehouseWorkerSalaryLevel::getSubclassLevel, gzPersonnelFoundation.getSubclassIevel())
                            .eq(GzWarehouseWorkerSalaryLevel::getDelStatus, YesNoEnum.NO.getKey()));
                    gzPersonnelFoundation.setBasicSalary(gzWarehouseWorkerSalaryLevel.getBaseSalary());
                    //岗位工资
                    gzPersonnelFoundation.setPostWage(gzWarehouseWorkerSalaryLevel.getAllowance());
                    gzPersonnelFoundation.setManagementAllowance(gzWarehouseWorkerSalaryLevel.getManagementAllowance());
                    gzPersonnelFoundation.setHouseaLlowance(gzWarehouseWorkerSalaryLevel.getHouseaLlowance());
                    gzPersonnelFoundation.setServiceExperienceAward(gzWarehouseWorkerSalaryLevel.getSeniorityPay());

                    gzPersonnelFoundation.setPerformanceCoefficient(gzWarehouseWorkerSalaryLevel.getPerformanceCoefficient());
                    gzPersonnelFoundation.setAchievementBonus(gzWarehouseWorkerSalaryLevel.getAchievementBonus());
                    gzPersonnelFoundation.setEvaluationCriteriaBonus(gzWarehouseWorkerSalaryLevel.getEvaluationCriteriaBonus());
                    gzPersonnelFoundation.setSocialSecuritySubsidies(gzWarehouseWorkerSalaryLevel.getSocialSecuritySubsidies());
                    // 加班费 全勤奖
                    gzPersonnelFoundation.setFullAttendanceBonus(gzWarehouseWorkerSalaryLevel.getFullAttendanceBonus());
                    gzPersonnelFoundation.setOvertimePay(gzWarehouseWorkerSalaryLevel.getOvertimePay());

                }

            }
        }

        return iGzPersonnelFoundationService.saveBatch(list) ? AjaxResult.success("导入成功") : AjaxResult.error();
    }


    @ApiOperation("导入有提示")
    @PreAuthorize("@ss.hasPermi('wages:personnelfoundation:add')")
    @Log(title = "导入有提示", businessType = BusinessType.INSERT)
    @PostMapping("/importListNote")
    public AjaxResult importListNote(MultipartFile file, boolean isUpdateSupport) throws Exception {
        if (file == null) {
            return AjaxResult.error("获取不到导入文件");
        }
        boolean excel = ExcelUtil.isExcel(file.getOriginalFilename());
        if (!excel) {
            return AjaxResult.error("导入文件格式错误，请导入excel文件");
        }
        // 导入新数据
        ExcelUtil<GzPersonnelFoundationVo> util = new ExcelUtil<GzPersonnelFoundationVo>(GzPersonnelFoundationVo.class);
        List<GzPersonnelFoundationVo> excelList = util.importCacheExcel(file.getInputStream());

        String message = iGzPersonnelFoundationService.importListNote(excelList, isUpdateSupport);
        return AjaxResult.success(message);


    }


    /**
     * @Description 导出
     * @Author gpframework
     * @Date 2024-01-18
     * @Param gzPersonnelFoundation
     * @Return TableDataInfo
     */

    @PreAuthorize("@ss.hasPermi('wages:personnelfoundation:export')" )
    @Log(title = "导出人员基础" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(GzPersonnelFoundationReq gzPersonnelFoundationReq) {
        QueryWrapper<GzPersonnelFoundation> lqw = new QueryWrapper<GzPersonnelFoundation>();
        gzPersonnelFoundationReq.generatorQuery(lqw,true);
        List<GzPersonnelFoundationVo> list = iGzPersonnelFoundationService.listVo(lqw);
        ExcelUtil<GzPersonnelFoundationVo> util = new ExcelUtil<GzPersonnelFoundationVo>(GzPersonnelFoundationVo. class);
        return util.exportExcel(list, "personnelfoundation" );
    }

    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-01-18
     * @Param gzPersonnelFoundation
     * @Return TableDataInfo
     */
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('wages:personnelfoundation:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult<GzPersonnelFoundationVo> getInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGzPersonnelFoundationService.getVoById(id));
    }



    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-01-18
     * @Param gzPersonnelFoundation
     * @Return TableDataInfo
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('wages:personnelfoundation:remove')" )
    @Log(title = "删除人员基础" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(iGzPersonnelFoundationService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }

    @ApiOperation("下载中转模板")
    @Log(title = "下载中转模板" , businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplateTransfer" )
    public AjaxResult importTemplateTransfer() {
        ExcelUtil<GzPersonnelFoundationTransferExcel> util = new ExcelUtil<GzPersonnelFoundationTransferExcel>(GzPersonnelFoundationTransferExcel.class);
        return util.importTemplateExcel("中转人员基础表");
    }

    @ApiOperation("下载档口模板")
    @Log(title = "下载档口模板" , businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplateGearopening" )
    public AjaxResult importTemplateGearopening() {
        ExcelUtil<GzPersonnelFoundationGearopeningExcel> util = new ExcelUtil<GzPersonnelFoundationGearopeningExcel>(GzPersonnelFoundationGearopeningExcel.class);
        return util.importTemplateExcel("档口人员基础表");
    }

    @ApiOperation("下载办公室文职模板")
    @Log(title = "下载办公室文职模板" , businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplateOfficeclerks" )
    public AjaxResult importTemplateOfficeclerks() {
        ExcelUtil<GzPersonnelFoundationOfficeclerksExcel> util = new ExcelUtil<GzPersonnelFoundationOfficeclerksExcel>(GzPersonnelFoundationOfficeclerksExcel.class);
        return util.importTemplateExcel("办公室文职人员基础表");
    }

    @ApiOperation("下载仓库人员模板")
    @Log(title = "下载仓库人员模板" , businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplateWarehouse" )
    public AjaxResult importTemplateWarehouse() {
        ExcelUtil<GzPersonnelFoundationWarehouseExcel> util = new ExcelUtil<GzPersonnelFoundationWarehouseExcel>(GzPersonnelFoundationWarehouseExcel.class);
        return util.importTemplateExcel("仓库人员基础表");
    }

    @ApiOperation("下载档口及办公室文职人员模板")
    @Log(title = "下载档口及办公室文职人员模板" , businessType = BusinessType.EXPORT)
    @GetMapping("/importOfficeclerksGearopening" )
    public AjaxResult importOfficeclerksGearopening() {
        ExcelUtil<GzPersonnelFoundationOfficeclerksGearopeningExcel> util = new ExcelUtil<GzPersonnelFoundationOfficeclerksGearopeningExcel>(GzPersonnelFoundationOfficeclerksGearopeningExcel.class);
        return util.importTemplateExcel("档口及办公室文职人员基础表");
    }




}
